/**
 * 
 */
package commons.base.util;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yuan<cihang.yuan@happyelements.com>
 * @since 1.7
 */
public class NamedThreadFactory implements ThreadFactory {
	
	private static final AtomicInteger poolNumber = new AtomicInteger(1);
	private final ThreadGroup group;
	private final AtomicInteger threadNumber = new AtomicInteger(1);
	private final String namePrefix;

	public NamedThreadFactory(String prefix) {
		SecurityManager localSecurityManager = System.getSecurityManager();
		this.group = ((localSecurityManager != null) ? localSecurityManager.getThreadGroup() : Thread.currentThread()
				.getThreadGroup());
		namePrefix = (prefix + "-pool-" + poolNumber.getAndIncrement() + "-thread-");
	}

	@Override
	public Thread newThread(Runnable runnable) {
		Thread localThread = new Thread(group, runnable, namePrefix + threadNumber.getAndIncrement(), 0L);
		if (localThread.isDaemon())
			localThread.setDaemon(false);
		if (localThread.getPriority() != Thread.NORM_PRIORITY)
			localThread.setPriority(Thread.NORM_PRIORITY);
		return localThread;
	}

}
